home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3411 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  65 lines

  1. Path: news.itd.umich.edu!clahey
  2. From: clahey@rep00703.reshall.umich.edu (Chris Lahey)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Nested Structures in C - A Question
  5. Date: 28 Jan 1996 20:03:35 GMT
  6. Organization: University of Michigan
  7. Message-ID: <CLAHEY.96Jan28200335@rep00703.reshall.umich.edu>
  8. References: <36400002@peg>
  9. NNTP-Posting-Host: rep00703.reshall.umich.edu
  10. In-reply-to: tmccoy@peg.apc.org's message of 29 Jan 96 01:38 GMT+1000
  11.  
  12. I believe that you are looking at this wrong.  Remember this.
  13. When you define a structure you say what data is going to go
  14. in it.  You give all of this data names.  A struct is just
  15. like any other data type (For what we're discussing.)  What 
  16. you are trying to do is almost equivelent to:
  17.  
  18. struct outer {
  19.     int var1;
  20.     int var2;
  21.     int var3;
  22.     double;
  23. };
  24.  
  25. It's not quite the same.  Yours will compile.  The struct inner
  26. is just useless.  You've defined a type and then ended your block.
  27. What you probably want is either
  28.  
  29. struct outer {
  30.     int var1;
  31.     int var2;
  32.     int var3;
  33.     struct {
  34.         int nested1;
  35.         int nested2;
  36.     } inner;
  37. };
  38.  
  39. which will allow you to access the inner structure as you wanted, 
  40. or
  41.  
  42. struct inner {
  43.     int nested1;
  44.     int nested2;
  45. };
  46.  
  47. struct outer {
  48.     int var1;
  49.     int var2;
  50.     int var3;
  51.     struct inner var4;
  52. };
  53.  
  54. which will not only allow you to access the inner structure as
  55. instance.var4 but also to create instances of the inner structure
  56. as normal variables.  In either case no memory is allocated until
  57. you create an instance of the struct.  A structure allocating
  58. memory when it sees struct inner {...} DUMMY; is very similar to
  59. it allocation memory when it sees int var1;.  Both are instances
  60. of a type (DUMMY is an instance of struct inner and var1 is an
  61. instance of int) and no memory should be allocated until an
  62. instance of the struct is declared outside a structure body.
  63. I hope I was helpful.  Good luck.
  64.     Chris
  65.